package com.longcai.cm.api.api4common;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.longcai.cm.auth.Login;
import com.longcai.cm.auth.LoginUser;
import com.longcai.cm.bean.Page;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.StringUtil;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.domain.*;
import com.longcai.cm.domain.vm.CarProxyViewModel;
import com.longcai.cm.domain.vm.VersionControl;
import com.longcai.cm.domain.vm.VipManagerViewModel;
import com.longcai.cm.moudules.system.bean.DicCode;
import com.longcai.cm.moudules.system.domain.SysDicValue;
import com.longcai.cm.moudules.system.service.SysDicCodeService;
import com.longcai.cm.service.*;
import com.longcai.cm.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author libingxing
 */
@RestController
@Api(tags = "通用信息相关")
@RequestMapping("/api/common")
public class ApiCommonController {

    @Resource
    private JaMemberOpinionService memberOpinionService;

    @Resource
    private SysDicCodeService sysDicCodeService;

    @Resource
    private JaHelpCenterService helpCenterService;

    @Resource
    private JaCarProxyTitleService carProxyTitleService;

    @Resource
    private JaCarProxyInfoService carProxyInfoService;

    @Resource
    private JaVersionControlService versionControlService;

    @GetMapping("/getCommonText")
    @ApiOperation("公共文本")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户协议 yhxy  隐私政策 yszc", name = "code", dataType = "int", required = true)
    })
    public String getCommonText(String code) {
        return sysDicCodeService.getTextValueByCode(code);
    }

    @Login
    @PostMapping("/getOrderCancelReason")
    @ApiOperation("订单取消原因")
    public R<List<String>> getOrderCancelReason() {
        return R.success(sysDicCodeService.getListValueByCode(DicCode.ORDER_CANCEL_REASON));
    }

    @Login
    @PostMapping("/getOrderRefundReason")
    @ApiOperation("订单退款原因")
    public R<List<String>> getOrderRefundReason() {
        return R.success(sysDicCodeService.getListValueByCode(DicCode.ORDER_REFUND_REASON));
    }

    @Login
    @PostMapping("/getCancelMemberReason")
    @ApiOperation("用户注销原因")
    public R<List<String>> getCancelMemberReason() {
        return R.success(sysDicCodeService.getListValueByCode(DicCode.MEMBER_CANCEL_REASON));
    }

    @Login
    @PostMapping("/enterOpinion")
    @ApiOperation("意见反馈")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "反馈内容", name = "content", dataType = "int", required = true),
            @ApiImplicitParam(value = "反馈图片(逗号分割)", name = "img", dataType = "int", required = true),
            @ApiImplicitParam(value = "联系方式", name = "contact", dataType = "int", required = true)
    })
    public R<Object> enterOpinion(
            @ApiIgnore @LoginUser FaMember member,
            String content, String img, String contact
    ) {
        final JaMemberOpinion memberOpinion = new JaMemberOpinion();
        memberOpinion.setId(StringUtil.getUuid());
        memberOpinion.setOpinionImg(img);
        memberOpinion.setContent(content);
        memberOpinion.setMemberId(member.getId());
        memberOpinion.setContact(contact);
        memberOpinion.setCreateTime(DateUtil.now());
        memberOpinionService.save(memberOpinion);
        return R.success();
    }

    @PostMapping("/helpCenter")
    @ApiOperation("帮助中心")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
    })
    public R<Page<List<JaHelpCenter>>> helpCenter(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows
    ) {
        final LambdaQueryWrapper<JaHelpCenter> wrapper = new LambdaQueryWrapper<>();
        final long total = helpCenterService.count(wrapper);
        final Page<List<JaHelpCenter>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        wrapper.orderByDesc(JaHelpCenter::getCreateTime);
        final List<JaHelpCenter> list = helpCenterService.list(wrapper);
        result.setContent(list);
        return R.success(result);
    }

    @GetMapping("/helpCenterInfo")
    @ApiOperation("帮助中心详情(html)")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id", dataType = "String", required = true)
    })
    public String helpCenterInfo(
            String id
    ) {
        final JaHelpCenter helpCenter = helpCenterService.getById(id);
        return helpCenter == null ? "" : helpCenter.getContent();
    }

    @Login
    @PostMapping("/carProxy")
    @ApiOperation("车务代办列表")
    public R<List<JaCarProxyTitle>> getCarProxy(
            @RequestParam(defaultValue = "1") String type
    ) {
        LambdaQueryWrapper<JaCarProxyTitle> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(type)) {
            query.eq(JaCarProxyTitle::getType, type);
        }
        final List<JaCarProxyTitle> list = carProxyTitleService.list(query);
        if (list.size() == 0) {
            return R.success(new ArrayList<>());
        }
        return R.success(list);
    }

    @Login
    @PostMapping("/getCarProxyInfo")
    @ApiOperation("车务代办业务")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "城市", name = "city", dataType = "String", required = true),
            @ApiImplicitParam(value = "县区（不必填）", name = "area", dataType = "String", required = true),
            @ApiImplicitParam(value = "代办列表id  5代驾 6道路救援", name = "proxyId", dataType = "String", required = true)
    })
    public R<List<CarProxyViewModel>> getCarProxyInfo(
            String city, String area, @RequestParam String proxyId
    ) {
        LambdaQueryWrapper<JaCarProxyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JaCarProxyInfo::getProxyId, proxyId);
        if (StringUtils.isNotBlank(city)) {
            wrapper.eq(JaCarProxyInfo::getCity, city);
        }
        if (StringUtils.isNotBlank(area)) {
            wrapper.eq(JaCarProxyInfo::getArea, area);
        }
        final List<JaCarProxyInfo> list = carProxyInfoService.list(wrapper);
        if (list.size() == 0) {
            return R.success(new ArrayList<>());
        }
        List<CarProxyViewModel> result = list.stream().map(
                value -> new CarProxyViewModel(value.getId(), value.getTitle(), value.getContent(), value.getContact())
        ).collect(Collectors.toList());
        return R.success(result);
    }

    @PostMapping("/carProxyInfo")
    @ApiOperation("车务代办详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "车务代办id", name = "id", dataType = "String", required = true)
    })
    public R<JaCarProxyInfo> carProxyInfo(
            String id
    ) {
        final JaCarProxyInfo carProxy = carProxyInfoService.getById(id);
        return R.success(carProxy);
    }

    @Login
    @PostMapping("/vipManager")
    @ApiOperation("会员管家")
    public R<VipManagerViewModel> vipManager() {
        final VipManagerViewModel result = new VipManagerViewModel();
        final List<SysDicValue> values = sysDicCodeService.getListByCode(DicCode.SINGLE_VIP_MANAGER);
        if (values.size() == 0) {
            result.setManagerList(new ArrayList<>());
        } else {
            result.setManagerList(values.stream().map(
                    value -> new CarProxyViewModel(value.getId(), value.getName(), value.getValue(), value.getRemark())
            ).collect(Collectors.toList()));
        }
        result.setMergeManagerContact(sysDicCodeService.getTextValueByCode(DicCode.MERGE_VIP_CONTACT));
        result.setMergeManagerQrCode(sysDicCodeService.getTextValueByCode(DicCode.MERGE_VIP_QR_CODE));
        return R.success(result);
    }

    @PostMapping("/getVersion")
    @ApiOperation("获取版本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前设备版本号", name = "versionNum", dataType = "int", required = true),
            @ApiImplicitParam(value = "设备型号 1安卓2ios", name = "device", dataType = "int", required = true)
    })
    public R<VersionControl> getVersion(
            String versionNum, String device
    ) {
        VersionControl versionControl = new VersionControl();
//        获取指定版本
        final JaVersionControl current = versionControlService.lambdaQuery()
                .eq(JaVersionControl::getVersionNum, versionNum)
                .eq(JaVersionControl::getDevice, device).one();
        versionControl.setCurrentVersion(current);
//        获取最新版本
        final JaVersionControl newVersion = versionControlService.lambdaQuery()
                .orderByDesc(JaVersionControl::getVersionNum)
                .eq(JaVersionControl::getDevice, device)
                .eq(JaVersionControl::getCheckState, 1)
                .last(" limit 1 ")
                .one();
        versionControl.setNewVersion(newVersion);
        if (newVersion != null) {
            if (current != null) {
//                判断版本号是否一致
                if (current.getVersionNum().equals(newVersion.getVersionNum())) {
//                    版本一致 不需要更新
                    versionControl.setNeedUpdate(2);
                } else {
                    versionControl.setNeedUpdate(1);
                }
            } else {
//                老版本直接覆盖
                versionControl.setNeedUpdate(1);
            }
        } else {
//            没新版本不用更新
            versionControl.setNeedUpdate(2);
        }
        return R.success(versionControl);
    }

}
